<template>
  <div id="main-container">
    <div id="outline-container">
      <el-card class="box-card-outline">
        <div class="header">已处理总数</div>
        <div class="content">{{getMsgCount.msgCount}}</div>
      </el-card>
      <el-card class="box-card-outline">
        <div class="header">处理比率</div>
        <div class="content">
          <span v-bind:style="{fontWeight:'bold'}">{{getMsgCount.processRatio}}</span> |
          <span v-bind:style="{color:'green',fontWeight:'bold'}">{{getMsgCount.chargeRatio}}</span> |
          <span v-bind:style="{color:'blue',fontWeight:'bold'}">{{getMsgCount.workRatio}}</span>
        </div>
      </el-card>
      <el-card class="box-card-outline charge">
        <div class="header">充电总数</div>
        <div class="content">
          <span v-bind:style="{fontWeight:'bold'}">{{getMsgCount.msgChargeCount}}</span> |
          <span v-bind:style="{color:'green',fontWeight:'bold'}">+{{getMsgCount.msgChargeIncrement}}</span>
        </div>
      </el-card>
      <el-card class="box-card-outline charge">
        <div class="header">充电细节</div>
        <div class="content"><span
          v-bind:style="{color:'green',fontWeight:'bold'}">{{getMsgCount.msgChargeCountFixed}}</span> | <span
          v-bind:style="{color:'red',fontWeight:'bold'}">{{getMsgCount.msgChargeCountVariable}}</span>
        </div>
      </el-card>
      <el-card class="box-card-outline work">
        <div class="header">工作总数</div>
        <div class="content">
          <span v-bind:style="{fontWeight:'bold'}">{{getMsgCount.msgWorkCount}}</span> |
          <span v-bind:style="{color:'green',fontWeight:'bold'}">+{{getMsgCount.msgWorkIncrement}}</span>
        </div>
      </el-card>
      <el-card class="box-card-outline work">
        <div class="header">工作细节</div>
        <div class="content"><span
          v-bind:style="{color:'green',fontWeight:'bold'}">{{getMsgCount.msgWorkCountFixed}}</span> | <span
          v-bind:style="{color:'red',fontWeight:'bold'}">{{getMsgCount.msgWorkCountVariable}}</span>
        </div>
      </el-card>
    </div>

    <div id="tcp-traffic-outline-bar"></div>

    <div id="item-container">
      <!--服务器连接状态-->
      <el-popover :key="kyItem.id" v-if="channelItems" v-for="kyItem in channelItems"
                  class="box-card-outline-item"
                  placement="top"
                  title="信息"
                  trigger="hover">
        <div>缓存消息：{{kyItem.count}}个</div>
        <div>工作状态：{{buttonItem(kyItem.enabled,kyItem.count).detail}}</div>
        <div v-if="!kyItem.enabled" :style="{color: 'red'}">该设备未接入</div>
        <el-button slot="reference" :style="{width: '100%', height: '100%' }"
                   v-bind:type="buttonItem(kyItem.enabled,kyItem.count).btnType">{{kyItem.id}}
        </el-button>
      </el-popover>
    </div>
  </div>
</template>

<script>
  import echarts from 'echarts'
  import { dataProcessOutline } from '@/api/data'
  import { setTimer, touchError } from '@/utils/timer'

  export default {
    name: 'dataProcessPressureOutline',
    data: function() {
      return {
        msgChargeCountLazy: 0,
        msgWorkCountLazy: 0,
        msgCount: null,
        channelItems: null,
        // 「服务器获取」设置报警的限定:负载的限定
        normalLimit: null,
        exceptionLimit: null,
        // Chart的引用
        myChartBarDetail: '待获取'
      }
    },
    computed: {
      getMsgCount() {
        if (this.msgCount === null) {
          return {
            msgCount: '待获取',
            msgChargeCount: '待获取',
            msgChargeCountFixed: '待获取',
            msgChargeCountVariable: '待获取',
            msgChargeIncrement: 0,
            msgWorkCount: '待获取',
            msgWorkCountFixed: '待获取',
            msgWorkCountVariable: '待获取',
            msgWorkIncrement: 0,
            processRatio: '待获取',
            chargeRatio: '待获取',
            workRatio: '待获取'
          }
        } else {
          this.msgCount.processRatio = ((this.msgCount.msgChargeCount + this.msgCount.msgWorkCount) / this.msgCount.msgCount * 100).toFixed(1) + '%'
          this.msgCount.chargeRatio = (this.msgCount.msgChargeCount / this.msgCount.msgCount * 100).toFixed(1) + '%'
          this.msgCount.workRatio = (this.msgCount.msgWorkCount / this.msgCount.msgCount * 100).toFixed(1) + '%'
          this.msgCount.msgChargeIncrement = this.msgCount.msgChargeCount - this.msgChargeCountLazy
          this.msgChargeCountLazy = this.msgCount.msgChargeCount
          this.msgCount.msgWorkIncrement = this.msgCount.msgWorkCount - this.msgWorkCountLazy
          this.msgWorkCountLazy = this.msgCount.msgWorkCount
          return this.msgCount
        }
      }
    },
    mounted: function() {
      // 初始化柱状图的模拟数据
      this.myChartBarDetail = echarts.init(document.getElementById('tcp-traffic-outline-bar'))
      this.myChartBarDetail.setOption(this.initBarDetail('random'))
      window.onresize = () => this.myChartBarDetail.resize()
      setTimer(this.getData, 3000)
    },
    methods: {
      // HTTP API 获取数据
      getData() {
        const vm = this
        dataProcessOutline().then(response => {
          vm.msgCount = response.data.msgCount
          vm.channelItems = response.data.channelItems
          vm.normalLimit = response.data.normalLimit
          vm.processRemoteData(response.data)
        }).catch(error => {
          touchError(this, this.getData, error)
        })
      },
      // 展示 Items 的样式动态设定
      buttonItem: function(enabled, count) {
        let btnType
        let detail
        if (count < this.normalLimit) {
          btnType = 'success'
          detail = '正常'
        } else if (count >= this.exceptionLimit) {
          btnType = 'danger'
          detail = '过载'
        } else {
          btnType = 'warning'
          detail = '繁忙'
        }
        if (!enabled) {
          btnType = 'info'
        }
        return { btnType: btnType, detail: detail }
      },
      // 根据缓存的消息数量，获取描述
      itemDescribe(count) {
        if (count < this.normalLimit) {
          return '正常'
        } else if (count >= this.exceptionLimit) {
          return '过载'
        } else {
          return '繁忙'
        }
      },
      // 处理从服务器获取的数据
      processRemoteData(response) {
        this.normalLimit = Number.parseInt(response.normalLimit)
        this.exceptionLimit = Number.parseInt(response.exceptionLimit)
        this.channelItems = response.channelItems

        this.myChartBarDetail.setOption(this.initBarDetail('response', response.channelItems))
      },
      // 初始化柱状图的模拟数据
      initBarDetail(type, channelItems) {
        let length = 10
        const xData = [] // 横坐标内容
        const msgCountData = [] // 消息计数
        const timeCostsData = [] // 消息处理的时间成本

        if (type === 'response') {
          length = channelItems.length
          for (let i = 0; i < length; i++) {
            const item = channelItems[i]
            xData.push(item.id + '组')
            msgCountData.push(item.count)
            timeCostsData.push(Math.round(item.count * 0.005))
          }
        } else {
          for (let i = 0; i < length; i++) {
            xData.push(i + 1 + '组')
            const value = Math.round(Math.random() * 500)
            msgCountData.push(value)
            timeCostsData.push(Math.round(value * 0.05))
          }
        }
        const ret = {
          title: {
            text: '数据处理压力图示',
            x: '100'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {}
          },
          legend: {
            align: 'left',
            right: '100',
            data: ['待处理(个)', '预计耗时(s)']
          },
          calculable: true,
          xAxis: [{
            type: 'category',
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitArea: {
              show: false
            },
            axisLabel: {
              interval: 0
            },
            data: xData
          }],
          yAxis: [{
            type: 'value',
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              interval: 0
            },
            splitArea: {
              show: false
            }
          }],
          dataZoom: [{
            show: true,
            height: 30,
            xAxisIndex: [
              0
            ],
            bottom: 0
            // start: this.barDataZoomStart,
            // end: this.barDataZoomEnd
          }],
          series: [{
            name: '待处理(个)',
            type: 'bar',
            stack: 'total',
            barMaxWidth: 50,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  formatter(p) {
                    return p.value + '个'
                  }
                }
              }
            },
            data: msgCountData
          }, {
            name: '预计耗时(s)',
            type: 'line',
            stack: 'total',
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  formatter(p) {
                    return p.value + ' s'
                  }
                }
              }
            },
            data: timeCostsData
          }]
        }
        if (type !== 'response') {
          console.log(ret)
          ret.dataZoom = [{
            show: true,
            height: 30,
            xAxisIndex: [
              0
            ],
            bottom: 0,
            start: 0,
            end: 20
          }]
        }
        return ret
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  #main-container {
    /*display: flex;*/
    font-weight: bold;
    padding: 0 10px;
  }

  /*********** outline ***********************/
  #outline-container {
    display: flex;
    /*flex-flow: wrap;*/
    justify-content: space-between;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);;

    .box-card-outline {
      max-width: 300px;
      height: 100px;
      flex: 2 1 auto;
      margin: 20px 10px;
      transition: 0.3s;
      cursor: pointer;
      background-color: rgba(0, 227, 230, 0.07);

      &:hover {
        background-color: rgba(255, 255, 255, 0.07);
      }

      .content {
        font-size: 130%;
        text-align: center;
        padding-top: 10px;
      }

      .header {
        color: rgba(0, 0, 0, 0.51);
        padding-bottom: 10px;
        text-align: center;
      }

    }
    .charge {
      background-color: rgba(22, 230, 0, 0.06);
    }
    .work {
      background-color: rgba(0, 45, 230, 0.07);
    }
  }

  /*********** echarts-bar-detail ***********************/
  #tcp-traffic-outline-bar {
    padding-top: 20px;
    width: 100%;
    height: 70vh;
  }

  /*********** item-container ***********************/

  #item-container {
    padding-top: 10px;
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
  }

  #item-container .box-card-outline-item {
    max-width: 80px;
    width: 80px;
    flex: 1 1 auto;
    margin: 10px 10px;
    transition: 0.3s;
    cursor: pointer;
  }
</style>
